package com.globallogic.jira.gadget.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Collections;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.project.Project;
import com.atlassian.jira.project.ProjectManager;
import com.atlassian.jira.project.version.Version;

/**
 * 
 * @author anton.pereverziev
 * 
 */
@SuppressWarnings("serial")
public class VersionsGetter extends HttpServlet {

	private static final Logger log = Logger.getLogger(VersionsGetter.class);

	@Override
	protected void doGet(final HttpServletRequest req,
			final HttpServletResponse resp) throws ServletException,
			IOException {
		log.debug("VersionsGetter started");
		final String projectName = req.getParameter("projectName");
		final String selectedVersion = req.getParameter("selected_version");
		final ProjectManager projectManager = ComponentManager.getInstance()
				.getProjectManager();
		if (projectName != null && !"".equals(projectName)) {
			final Project project = projectManager
					.getProjectObjByName(projectName);
			resp.setContentType("text/html");
			final PrintWriter writer = resp.getWriter();
			writer.println("<option value=\"All\" selected>All</option>");
			writer.println("<option value=\"NULL\">Unversioned</option>");
			Collection<Version> versions = null;
			if (project != null) {
				versions = project.getVersions();
				if (versions == null)
					versions = Collections.EMPTY_LIST;
				resp.setContentType("text/html");
				for (final Version version : versions) {
					if (selectedVersion != null
							&& selectedVersion.equals(version.getName())) {
						writer.println("<option selected value=\""
								+ version.getName() + "\">" + version.getName()
								+ "</option>");
					} else {
						writer.println("<option value=\"" + version.getName()
								+ "\">" + version.getName() + "</option>");
					}
				}
				writer.flush();
				writer.close();
			} else {
				log.warn("Project is null");
			}
		}
		log.debug("VersionsGetter finished");
	}
}